package edu.tjhsst.androidIntranet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import edu.tjhsst.androidIntranet.login.AllTrustManager;
import edu.tjhsst.androidIntranet.login.AllVerifier;

public class PageLoader {

	private static StringBuffer page = new StringBuffer();
	private static boolean doneLoading = false;
	//private static final String TAG = "PageLoader";

	/**
	 * Loads the content at the subURL argument relative to the
	 * {@link IntranetManager#SERVER} variable The content downloaded can be
	 * retrieved by calling {@link PageLoader#getPage()}
	 * 
	 * @param subURL
	 *            the location of the content to be downloaded, relative to
	 *            {@link IntranetManager#SERVER}
	 */

	public static void downloadPage(final String subURL) {
		doneLoading=false;
		//To override the new SSL certificate of the Intranet. Instructions from http://groups.google.com/group/android-developers/browse_thread/thread/91d5ef794d763814 and http://www.jleeonline.com/?p=25
		HttpsURLConnection.setDefaultHostnameVerifier(new AllVerifier());
		try {
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { new AllTrustManager() }, null);
			HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		try {
			URL url = new URL(IntranetManager.SERVER+subURL);
			//Log.d("PageLoader", "Opening URL: " + IntranetManager.SERVER+subURL);
			URLConnection conn = url.openConnection();
			//conn.setDoOutput(true);
			conn.setDoInput(true);
			//conn.setRequestProperty("Origin", "http://iodine.tjhsst.edu/");
			//conn.setRequestProperty("Referer", IntranetManager.SERVER);
			//Log.d("PageLoader", "Cookie: "+IntranetManager.getCookies());
			conn.setRequestProperty("Cookie",IntranetManager.getCookies());

			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				page.append(line);
			}
			rd.close();
			doneLoading=true;
		} catch(IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns the content that was previously downloaded using the method. If loading is in progress, this method blocks until the content is downloaded
	 * {@link #downloadPage(String)}
	 * 
	 * @return a {@link StringBuffer} containing the page content
	 */

	public static StringBuffer getPage() {
		while(!doneLoading) {
			Thread.yield();
		}
		return page;
	}

}
